package com.itheima.web.controller.system;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.system.Permission;
import com.itheima.domain.system.Role;
import com.itheima.domain.system.User;
import com.itheima.utils.BeanUtil;
import com.itheima.utils.MD5Util;
import com.itheima.web.controller.BaseServlet;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/system/user")
public class UserServlet extends BaseServlet {
    public void userRoleList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");

        User user = userService.findById(id);
        //将数据加载到指定区域,供页面获取
        request.setAttribute("user", user);

        //调用业务层接口delete
        List<Role> allRoleByUserId = roleService.findAllRoleByUserId(id);
        request.setAttribute("userRoleList", allRoleByUserId);

        request.getRequestDispatcher("/WEB-INF/pages/system/user/user-role-add.jsp").forward(request, response);
    }

    public void updateRole(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userId = request.getParameter("userId");
        String[] roleIds = request.getParameterValues("ids");

        userService.updateRole(userId, roleIds);

        response.sendRedirect(request.getContextPath() + "/system/user?operation=list");
    }

    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String str = request.getParameter("str");
        if(StringUtils.isNotBlank(str)){
            findByName(request,response);
            return;
        }
        //进入列表页
        //获取数据
        int page = 1;
        int size = 5;
        if (StringUtils.isNotBlank(request.getParameter("page"))) {
            page = Integer.parseInt(request.getParameter("page"));
        }
        if (StringUtils.isNotBlank(request.getParameter("size"))) {
            size = Integer.parseInt(request.getParameter("size"));
        }
        PageInfo all = userService.findAll(page, size);
        //交数据保存到指定的位置
        request.setAttribute("page", all);
        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/system/user/user-list.jsp").forward(request, response);
    }

    public void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/system/user/user-add.jsp").forward(request, response);
    }

    public void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //将数据获取到，封装成一个对象
        User user = BeanUtil.fillBean(request, User.class);
        //调用业务层save
        userService.save(user);
        //跳转到页面list
        response.sendRedirect(request.getContextPath() + "/system/user?operation=list");
    }

    public void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //查询要修改的数据findById
        String id = request.getParameter("id");
        User user = userService.findById(id);
        //将数据加载到指定区域,供页面获取
        request.setAttribute("user", user);
        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/system/user/update.jsp").forward(request, response);

    }

    public void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //将数据获取到，封装成一个对象
        User user = BeanUtil.fillBean(request, User.class);
        //调用业务层接口update
        userService.update(user);
        //
        response.sendRedirect(request.getContextPath() + "/system/user?operation=list");

    }

    public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String arr = request.getParameter("id");
        String[] split = arr.split(",");
        //调用业务层接口delete
        for (String s : split) {
            userService.delete(s);
        }

        response.sendRedirect(request.getContextPath() + "/system/user?operation=list");

    }


    public void show(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //查询要修改的数据findById
        String id = request.getParameter("id");
        //调用业务层方法
        User user = userService.findById(id);
        System.out.println(user);
        //将数据加载到指定区域,供页面获取
        request.setAttribute("user", user);
        //调用业务层接口delete
        List<Role> allRoleByUserId = roleService.findAllRoleByUserId(id);
        List<Role> userRoleList = new ArrayList<>();
        for (Role role : allRoleByUserId) {
            if("1".equals(role.getFlag())){
                userRoleList.add(role);
            }
        }
        request.setAttribute("userRoleList", userRoleList);
        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/system/user/user-show.jsp").forward(request, response);
    }


    public void change(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //查询要修改的数据findById
        String id = request.getParameter("id");
        //System.out.println(id);
        //调用业务层方法
        User user = userService.findById(id);
        int status = user.getStatus();

        status = status == 0 ? 1 : 0;

        user.setStatus(status);
        userService.update(user);
        //将数据加载到指定区域,供页面获取
        request.setAttribute("user", user);
        list(request, response);
        //跳转页面
//        response.sendRedirect(request.getContextPath() + "/system/user?operation=list");
    }



    public void findByName(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String value = request.getParameter("str");
        String sizeStr = request.getParameter("size");
        int size=Integer.parseInt(sizeStr);
        //System.out.println(value);
        //进入列表页获取数据
        int page = 1;

        if (StringUtils.isNotBlank(request.getParameter("page"))){
            page=Integer.parseInt(request.getParameter("page"));
        }

        PageInfo all = userService.findByName(page, size, value);
        //将数据保存到指位置
        request.setAttribute("page",all);
        request.setAttribute("str",value);
        //跳转页面
        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/system/user/user-list.jsp").forward(request,response);

    }

   /* *//**
     * 异步校验email
     * *//*
    public void checkEmail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取email
        String email = request.getParameter("email");
        int count = userService.findByEmail(email);
        //判断
        PrintWriter writer = response.getWriter();
        if (count == 0){
            //email可用
            writer.write("<font color='green'>email可用</font>");
        }else{
            //email不可用
            writer.write("<font color='red'>email已存在,不可用</font>");
        }
    }*/


    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //获取请求参数
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        //获取是否自动登录勾选标识
        String autoFlag=request.getParameter("ck");
        User user=userService.login(username,password);
        if(user != null) {
            //用户存在，并且有勾选标识，将用户的登录信息存入cookie中
            if(autoFlag!=null &&  !autoFlag.isEmpty()){
                Cookie cookie = new Cookie("user", username+"&"+password);
                cookie.setMaxAge(10*24*60*60);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
            request.getSession().setAttribute("loginUser", user);
            //如果登录成功，加载该用户对应的角色对应的所有模块
            List<Permission> permissionList = userService.findPermissionById(user.getId());
//            request.setAttribute("permissionList",permissionList);
            request.getSession().setAttribute("permissionList",permissionList);

            //当前登录用户对应的可操作模块的所有url拼接成一个大的字符串
            StringBuffer sbf = new StringBuffer();
            for(Permission permission: permissionList){
                sbf.append(permission.getUrl());
                sbf.append(',');
            }
            request.getSession().setAttribute("authorStr",sbf.toString());

            //跳转页面
            request.getRequestDispatcher("/WEB-INF/pages/home/main.jsp").forward(request, response);
        }else{
            request.setAttribute("msg","用户名或密码错误！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }

    public void changePwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取要修改的用户id
        String userId=request.getParameter("userId");
        //获取旧密码
        String oldPwd = request.getParameter("oldPwd");
        //获取新密码
        String newPwd=request.getParameter("newPwd");
        User user=userService.findUserById(userId);
        PrintWriter writer = response.getWriter();
        String dataStr="";
        if(user==null){
            //用户不存在
            dataStr="该用户不存在！";
        }else{
            if(!MD5Util.md5(oldPwd).equals(user.getPassword())){
                dataStr="输入的旧密码不正确，请重新输入！";
            }else{
                //旧密码正确，修改密码
                userService.updatePwdById(userId,newPwd);
                dataStr="修改成功，请重新登录！";
            }
        }
        writer.write(dataStr);
    }

    public void toLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.getRequestDispatcher("/login.jsp").forward(request,response);
        response.sendRedirect(request.getContextPath()+"/login.jsp");
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().removeAttribute("loginUser");
        request.getSession().removeAttribute("permissionList");
        response.sendRedirect(request.getContextPath()+"/login.jsp");
    }

}
